import { useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import { Alert, Button, Col, Dropdown, List, Row, Tabs } from 'antd';
import cs from 'classnames';

import { store } from '@/store';

import { TimeSort } from '@/enum';
import {
  roleAdd,
  roleDelete,
  roleList as roleListApi
} from '@/services/base/jiaoseguanlijiaosexiangguanjiekou';
import { Icon } from '@iconify/react/dist/iconify.js';

import Auth from './auth';
import DataAuth from './data-auth';
import Edit, { EditRef } from './edit';
import styles from './index.module.scss';
import User from './user';

export type BizObject = BASE.Role;

const Page: React.FC = () => {
  const edit = useRef<EditRef>(null);
  const roleList = useRequest(
    async () => {
      return (
        await roleListApi({
          timeSort: TimeSort.倒序
        })
      ).data;
    },
    {
      onSuccess: (res) => {
        if (!selectRole && res?.length) {
          setSelectRole(res[0]);
        }
      }
    }
  );
  const [selectRole, setSelectRole] = useState<BASE.Role>();

  // 复制角色
  const copyRole = (role: BASE.Role) => {
    store.app?.modal.confirm({
      title: '确认复制',
      content: `确认复制角色：${role.roleName}？`,
      onOk: async () => {
        await roleAdd({
          ...role,
          roleName: `${role.roleName}（复制）`,
          roleCode: `${role.roleCode}_copy`
        });
        store.app?.message.success('复制成功');
        roleList.refresh();
      }
    });
  };

  // 编辑角色
  const editRole = (role: BASE.Role) => {
    edit.current?.open({
      type: 'edit',
      rowData: role,
      onSuccess: () => {
        roleList.refresh();
      }
    });
  };

  // 删除角色
  const deleteRole = async (role: BASE.Role) => {
    store.app?.modal.confirm({
      title: '确认删除',
      content: `确认删除角色：${role.roleName}？`,
      onOk: async () => {
        await roleDelete({ id: role.id } as unknown as ArgumentsType<typeof roleDelete>[0]);
        store.app?.message.success('删除成功');
        const res = await roleList.refreshAsync();

        if (selectRole?.id === role.id) {
          setSelectRole(res?.[0]);
        }
      }
    });
  };

  return (
    <>
      <Row gutter={[24, 24]}>
        <Col md={4}>
          <>
            <List
              header={
                <>
                  <Button
                    onClick={() => {
                      edit.current?.open({
                        type: 'add',
                        onSuccess: () => {
                          roleList.refresh();
                        }
                      });
                    }}
                    icon={<Icon icon="ri:add-fill" />}
                    type="text"
                  >
                    创建角色
                  </Button>
                </>
              }
              bordered
              dataSource={roleList.data}
              renderItem={(item) => (
                <List.Item
                  className={cs(styles['item'], {
                    [styles['active']]: selectRole?.id === item.id
                  })}
                  onClick={setSelectRole.bind(null, item)}
                >
                  <div>{item.roleName}</div>

                  {![import.meta.env.VITE_SUPER_ADMIN].includes(item.roleCode) && (
                    <Dropdown
                      menu={{
                        items: [
                          { label: '复制', key: 'copy', onClick: copyRole.bind(null, item) },
                          { label: '编辑', key: 'edit', onClick: editRole.bind(null, item) },
                          { label: '删除', key: 'delete', onClick: deleteRole.bind(null, item) }
                        ]
                      }}
                    >
                      <Button icon={<Icon icon="ri:settings-3-fill" />} type="text" />
                    </Dropdown>
                  )}
                </List.Item>
              )}
            />
          </>
        </Col>
        <Col md={20}>
          {selectRole && selectRole.roleExplain && (
            <Alert type="info" message={selectRole.roleExplain} />
          )}

          <Tabs
            items={[
              { label: '角色员工', key: '角色员工', children: <User role={selectRole} /> },
              { label: '角色权限', key: '角色权限', children: <Auth role={selectRole} /> },
              { label: '数据权限', key: '数据权限', children: <DataAuth role={selectRole} /> }
            ]}
          />
        </Col>
      </Row>

      <Edit ref={edit} />
    </>
  );
};

export default Page;
